package controllers

import (
	"2301_news/cache"
	"2301_news/models"
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

type NewsController struct {
	beego.Controller
}

var ctx = context.Background()

func (c *NewsController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	status, _ := c.GetInt("status")
	if title == "" || time == "" || status != 1 || status != 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加参数信息不能为空",
		}
		c.ServeJSON()
		return
	}
	var news models.News
	news.Title = title
	news.Time = time
	news.Status = status
	err := news.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	newss, _ := news.List()
	jsonData, _ := json.Marshal(newss)
	cache.Rdb.Set(ctx, "news", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
}
func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	var news models.News
	news.ID = uint(id)
	err := news.Del()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	newss, _ := news.List()
	jsonData, _ := json.Marshal(newss)
	cache.Rdb.Set(ctx, "news", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
}
func (c *NewsController) Update() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}
	title := c.GetString("title")
	time := c.GetString("time")
	status, _ := c.GetInt("status")
	var news models.News
	news.ID = uint(id)
	news.Title = title
	news.Time = time
	news.Status = status
	err := news.Update()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	newss, _ := news.List()
	jsonData, _ := json.Marshal(newss)
	cache.Rdb.Set(ctx, "news", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 500,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
